//
//  TLanguageManager.m
//  Total
//
//  Created by xin on 2017/6/28.
//  Copyright © 2017年 elephants. All rights reserved.
//

#import "TLanguageManager.h"
#import "TLanguageEntity.h"

NSString * const TLanguageChangeNotification = @"TLanguageChange";

@interface TLanguageManager()

//当前的语言对象
@property (nonatomic,strong) TLanguageEntity * languageEntity;

@end

@implementation TLanguageManager

static TLanguageManager * instance;

+ (id)sharedManager {
    
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = [[TLanguageManager alloc] init];
        
        //读取plist表,把字典数组转为模型数组
        NSMutableArray * plist = [TLanguageEntity mj_objectArrayWithFilename:@"language.plist"];
        instance.languageList = [NSArray arrayWithArray:plist];
        
        //读取本地化的语言对象
        NSData * entityData = [[NSUserDefaults standardUserDefaults] objectForKey:@"languageEntity"];
        TLanguageEntity * entity = [NSKeyedUnarchiver unarchiveObjectWithData:entityData];
        
        if (entity == NULL) {
            instance.languageEntity = instance.languageList[0];
        }
        else{
            instance.languageEntity = entity;
        }
        
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (NSString *)getStringForKey:(NSString *)key withTable:(NSString *)table
{
    //根据当前的语言读取当前的语言文件名称
    NSString *path = [[NSBundle mainBundle] pathForResource:instance.languageEntity.languageFilePath ofType:@"lproj"];
    
    return [[NSBundle bundleWithPath:path] localizedStringForKey:key value:nil table:table];
}

- (void)changeLanguage:(TLanguageEntity *)entity
{
    NSLog(@"%s",__func__);
    
    instance.languageEntity = entity;
    
    //当前语言持久化到app内，下次启动app读取使用 保存
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:_languageEntity];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"languageEntity"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //给所有UI发送通知去更新
    [[NSNotificationCenter defaultCenter] postNotificationName:TLanguageChangeNotification object:nil];
}

@end
